package com.wink_172.library.utils

import android.os.Build
import android.util.Log
import com.alibaba.fastjson.JSON
import com.wink_172.library.callback.ICallback
import com.wink_172.library.model.Constants
import com.wink_172.library.model.Constants.SHARE_PATH
import com.wink_172.library.model.json.Data100
import com.wink_172.library.model.json.Data101
import com.wink_172.library.model.json.FileData
import com.wink_172.library.utils.LogUtil
import org.xutils.common.Callback
import org.xutils.http.RequestParams
import org.xutils.http.app.HttpRetryHandler
import org.xutils.http.request.UriRequest
import org.xutils.x


/**
 * 网络请求工具
 * */
object HttpRequest {

    private const val TAG = "HttpRequest"

    /**
     * 获取携带签名的请求
     * */
    fun getTargetParams(url: String): RequestParams {
        val params = RequestParams(url)

        params.maxRetryCount = 0//https://www.jianshu.com/p/116bb01e2e2b
        params.httpRetryHandler = object : HttpRetryHandler() {
            override fun canRetry(
                request: UriRequest,
                ex: Throwable,
                count: Int
            ): Boolean {//这个callback用的非常巧妙    //这里因为不能传递非Serialiazable,对象 所以需要精简代码
//                if (count == params.maxRetryCount) {
//                    //count         重试次数
//                    //maxRetryCount 最大重试次数
//                }
//                if (count > params.maxRetryCount) {
//                    return false;   //重试次数大于最大重试次数时，退出重试
//                }
                return false;
            }
        }

        params.addBodyParameter("osversion", Build.VERSION.RELEASE)
        params.addBodyParameter("app", "2")//客户端 1 ios， 2 Android


//            params.addHeader("host", com.wink_172.Constants2.OFFICAL_URL)
//            params.addHeader("HOST", com.wink_172.Constants2.OFFICAL_URL)
//            params.setHeader("Host", com.wink_172.Constants2.OFFICAL_URL)


//        Log.e(TAG, "hello02: ====>>"+params.headers[0].key+"   :"+ params.headers[0].value)
        return params;
    }

    /**
     *获取服务器文件夹的所有图片
     */
    fun get_test_imge_listbb(callback: ICallback?) {

        val params =
            HttpRequest.getTargetParams("http://106.52.115.24:8888/down/" + Constants.SHARE_PATH)
//        params.addBodyParameter("room_id", room_id)

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {

                LogUtil.appendToLog(result)

                val array = result.replace(" ", "").replace("\n", "").split("\">下载</a>")
//                Log.e(TAG, "array: ====>>" + array.size)
                val flag_path = "href=\"/down/" + SHARE_PATH + "?fname="
//                Log.e(TAG, "base url: ====>>http://106.52.115.24:8888/down/Cr07eT3BM94K?fname=testimage/" )

                val image_list: MutableList<FileData> = ArrayList()
                for (single in array) {
                    val start = single.indexOf(flag_path)
//                    Log.e(TAG, "start: ====>>" + start + "   all:" + single.length)
                    if (start == -1) {
                        continue
                    }
//                    Log.e(TAG, "single====>>: "+single )

                    val ext = if (single.contains(".jpg")) {
                        ".jpg"
                    } else if (single.contains(".jpeg")) {
                        ".jpeg"
                    } else if (single.contains(".JEPG")) {
                        ".JEPG"
                    } else if (single.contains(".JPG")) {
                        ".JPG"
                    } else if (single.contains(".PNG")) {
                        ".PNG"
                    } else if (single.contains(".png")) {
                        ".png"
                    } else if (single.contains(".txt")) {
                        ".txt"
                    } else if (single.contains(".apk")) {
                        ".apk"
                    } else if (single.contains(".pdf")) {
                        ".pdf"
                    } else if (single.contains(".mp4")) {
                        ".mp4"
                    } else if (single.contains(".exe")) {
                        ".exe"
                    } else {
                        ".png"
                    }

                    //single.indexOf(ext)//包含多个就会出错
                    val end = single.indexOf(ext) + ext.length
//                    Log.e(TAG, "end: ====>>" + end)
                    if (end == -1) {
                        continue
                    }

                    val bbc = single.substring(start, single.length).replace("href=\"", "")
                    val picture = FileData()
                    picture.web_url = bbc
                    picture.other = flag_path
                    image_list.add(picture)

//                    Log.e(TAG, "single: ====>>" + bbc)


                }
                callback?.onSendEvent(Constants.EventEnum.网络请求成功.ordinal, image_list)

            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {}
        }
        x.http().get(params, commonCallback)
    }

    /**
     *模板
     */
    @JvmStatic
    fun getVersionControl(callback: ICallback?) {
        val params = getTargetParams("https://github.com/3585682171/bbc2")
//        params.addHeader("Content-Type", "application/json")

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
//                LogUtil.appendToLog(result)

//                Log.e(TAG, "callback: ====>>"+ result)

                callback?.onSendEvent(Constants.EventEnum.网络请求成功.ordinal)
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
//                Log.e(TAG, "callback: ====>>"+ ex.message)
//                Log.e(TAG, "onSendEvent: ====>>github网络请求失败", )
            }

            override fun onCancelled(cex: Callback.CancelledException) {

            }

            override fun onFinished() {

            }
        }
        x.http().get(params, commonCallback)
    }


    /**
     *模板
     */
    fun themp1(callback: ICallback?) {
        val params = getTargetParams("https://apiv2.idata.cn:4430/post/chatgpt")
        params.addHeader("Content-Type", "application/json")
//        params.addBodyParameter("room_id", room_id)
//        Log.e(TAG, "advancedRoomGet: ====>>$params")

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
                LogUtil.appendToLog(result)

//                Log.e(TAG, "callback: ====>>"+ result)
                val array = result.split(".jpg")

                Log.e(TAG, "callback: ====>>" + array.size)
                for (single in array) {

                    Log.e(
                        TAG,
                        "single: ====>>" + single.substring(single.length - 10, single.length - 1)
                    )

                }

//                val data1 = JSON.parseObject(
//                    commonInfo.data,
//                    Data1::class.java
//                )

//                if (callback != null) {
//                    callback.onSendEvent(Constants.EventEnum.网络请求成功.ordinal)
//                }
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                Log.e(TAG, "callback: ====>>" + ex.message)
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {}
        }
        x.http().post(params, commonCallback)
    }

    /**
     *获取服务器文件夹的所有图片
     */
    fun get_test_imge_list(callback: ICallback?) {
        val params = getTargetParams("http://ip:8080/download/testimage/")
//        params.addBodyParameter("room_id", room_id)

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
                LogUtil.appendToLog(result)

                val array = result.split("</tt></a></td>")
                Log.e(TAG, "base url: ====>>http://ip:8888/down/Cr07eT3BM94K?fname=testimage/")
                var pos = 0
                for (single in array) {
                    val start = single.indexOf("/download/testimage")

                    val bb = if (single.contains(".jpg")) {
                        ".jpg"
                    } else if (single.contains(".jpeg")) {
                        ".jpeg"
                    } else {
                        ".png"
                    }

                    val end = single.indexOf(bb) + bb.length
                    if (start == -1 || end == -1) {
                        continue
                    }
                    pos++
                    Log.e(TAG, "single: ====>>pos:" + pos + "   " + single.substring(start, end))
                }
                Log.e(TAG, "callback: ====>>" + pos)
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {}
        }
        x.http().post(params, commonCallback)
    }

}